import storage from 'store'
import { login, profile } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    actorId: '',
    name: '',
    welcome: '',
    otherInfo: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INFO: (state, {
      actorId,
      name,
      ...otherInfo
    }) => {
      state.actorId = actorId
      state.name = name
      state.welcome = welcome()
      state.otherInfo = otherInfo
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(content => {
          storage.set(ACCESS_TOKEN, content, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', content)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    GetInfoMock ({ commit }) {
      commit('SET_INFO', {
        actorId: 1,
        name: '本地测试',
        welcome: welcome(),
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        profile().then((content) => {
          content.welcome = welcome()
          content.avatar = 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
          commit('SET_INFO', content)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_INFO', {
        name: '',
        welcome: '',
        actorId: '',
        avatar: ''
      })
      storage.remove(ACCESS_TOKEN)
    }

  }
}

export default user
